import psycopg2
import sys

def test_isolation_levels():
    connection = None
    try:
        connection = psycopg2.connect(
            user="postgres",
            password="votre_mot_de_passe",
            host="localhost",
            port="5432",
            database="transaction_lab"
        )

        connection.autocommit = False

        isolation_levels = [
            psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED,
            psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ,
            psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE
        ]
        
        isolation_names = [
            "READ COMMITTED",
            "REPEATABLE READ",
            "SERIALIZABLE"
        ]
        
        for i, level in enumerate(isolation_levels):
            connection.set_isolation_level(level)
            cursor = connection.cursor()
            
            print(f"\nTest avec niveau d'isolation: {isolation_names[i]}")
            
            # Lire le solde actuel
            cursor.execute("SELECT balance FROM accounts WHERE account_id = 1")
            balance = cursor.fetchone()[0]
            print(f"Solde initial: {balance} €")
            
            # Effectuer une modification
            cursor.execute("UPDATE accounts SET balance = balance + 10 WHERE account_id = 1")
            
            cursor.execute("SELECT balance FROM accounts WHERE account_id = 1")
            updated_balance = cursor.fetchone()[0]
            print(f"Solde après modification (non validée): {updated_balance}€")
            
            # Valider ou annuler la transaction
            if i < len(isolation_levels) - 1:
                connection.rollback()
                print("Transaction annulée")
            else:
                connection.commit()
                print("Transaction validée")
            
            cursor.close()
            
    except (Exception, psycopg2.Error) as error:
        # 关键修复：处理非UTF-8字符
        error_msg = str(error)
        # 将错误信息转换为UTF-8编码（替换无法解码的字符）
        safe_error_msg = error_msg.encode('utf-8', 'replace').decode('utf-8')
        print(f"Erreur lors du test des niveaux d'isolation: {safe_error_msg}")
    finally:
        if connection is not None:
            connection.close()

if __name__ == "__main__":
    test_isolation_levels()